package main

import (
	"encoding/xml"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

type Speak struct {
	XMLName xml.Name `xml:"speak"`
	Version string   `xml:"version,attr"`
	Lang    string   `xml:"xml:lang,attr"`
	Voice   []Voice  `xml:"Voice"`
}
type Voice struct {
	XMLName   xml.Name `xml:"voice"`
	Name      string   `xml:"name,attr"`
	Lang      string   `xml:"xml:lang,attr"`
	InnerText string   `xml:",innerxml"`
}

var url = "https://westus.api.cognitive.microsoft.com/sts/v1.0/issueToken"
var baseUrl = "https://westus.tts.speech.microsoft.com/"
var subscription_key = "fc700fc2c8914dc796720f2a4f9553a6"
var input = "A US senior official recently “warned” the UK on its approval to let Chinese telecoms company Huawei to help build some non-core parts of 5G data network, saying that it could allow China to “control the internet of the future” and “divide Western alliances through bits and bytes”."
var timeTemple = "20190513-0000"
var path = "cognitiveservices/v1"

func main() {
	client := &http.Client{}
	//提交请求
	reqest, err := http.NewRequest("POST", url, nil)
	//增加header选项
	reqest.Header.Add("Ocp-Apim-Subscription-Key", subscription_key)
	if err != nil {
		panic(err)
	}
	//处理返回结果
	response, _ := client.Do(reqest)
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(string(body))
	accessToken := string(body)
	constructedUrl := baseUrl + path

	speak := Speak{Version: "1.0", Lang: "en-us"}
	speak.Voice = append(speak.Voice, Voice{Name: "en-US-Guy24kRUS", Lang: "en-us", InnerText: input})
	data, _ := xml.MarshalIndent(&speak, "", "  ")
	bodyStr := string(data)

	//read, w := io.Pipe()
	//defer read.Close()
	//defer w.Close()
	//_, err = read.Read([]byte(bodyStr))

	reqest, err = http.NewRequest("POST", constructedUrl, strings.NewReader(bodyStr))
	//增加header选项

	reqest.Header.Add("Authorization", "Bearer "+accessToken)
	reqest.Header.Add("Content-Type", "application/ssml+xml")
	reqest.Header.Add("X-Microsoft-OutputFormat", "riff-24khz-16bit-mono-pcm")
	reqest.Header.Add("User-Agent", "YOUR_RESOURCE_NAME")
	if err != nil {
		panic(err)
	}
	//处理返回结果
	response, _ = client.Do(reqest)
	defer response.Body.Close()

	if response.StatusCode == 200 {
		body, err = ioutil.ReadAll(response.Body)
		if err != nil {
			fmt.Println(err)
		}
		content := []byte(body)
		//将指定内容写入到文件中
		nameStr := "sample-" + time.Now().Format(timeTemple) + ".wav"
		err := ioutil.WriteFile(nameStr, content, 0666)
		if err != nil {
			fmt.Println("ioutil WriteFile error: ", err)
		}
	} else {
		fmt.Println("\nStatus code: ", string(response.StatusCode), "\nSomething went wrong. Check your subscription key and headers.\n")
	}
}
